﻿@inject RecognizerService RecognizerService

<div class="row">
    <div class="col-12 col-sm-6 text-center">
        <SpeechWave Show="Start" TotalTime="5000" OnTimeout="OnTimeout" class="my-3" />
        <Button Text="@ButtonText" Icon="fa-fw fa-solid fa-microphone" OnClick="OnStart" />
    </div>
    <div class="col-12 col-sm-6">
        <Textarea Value="@Result" rows="6" />
    </div>
</div>

@code {
    private bool Start { get; set; }

    private string? Result { get; set; }

    private string ButtonText { get; set; } = "开始识别";

    private async Task OnStart()
    {
        if (ButtonText == "开始识别")
        {
            await RecognizerService.RecognizeOnceAsync(Recognize, 5000);
        }
        else
        {
            Start = false;
            ButtonText = "开始识别";
            StateHasChanged();
            await RecognizerService.CloseAsync(Recognize);
        }
    }

    private async Task OnTimeout()
    {
        await RecognizerService.CloseAsync(Recognize);
    }

    private Task Recognize(RecognizerStatus status, string? result)
    {
        if (status == RecognizerStatus.Start)
        {
            Start = true;
            ButtonText = "结束识别";
        }
        else if (status == RecognizerStatus.Finished)
        {
            Result = result;
            Start = false;
            ButtonText = "开始识别";
        }
        else
        {
            Result = "";
            Start = false;
            ButtonText = "开始识别";
        }
        StateHasChanged();
        return Task.CompletedTask;
    }
}
